<script lang="ts" setup>
  import { useRouter } from 'vue-router';
  import dayjs from 'dayjs';
  import { Message, Modal } from '@arco-design/web-vue';
  import { ref, onMounted } from 'vue';
  import useTable from '@/hooks/table';
  import { Game, GameSearchParams } from '@/types/game';
  import { publishGame, deleteGame, getGameList } from '@/api/game';
  import GameCard from '@/components/game-card/index.vue';
  import { GameRegionLevels, GameTypes, GameGroupTypes } from '@/config/game';
  import ProvinceJSON from '@/config/province.json';
  import CityJSON from '@/config/city.json';
  import SearchForm from './search-form.vue';

  const router = useRouter();

  const { pager, loading, total, list } = useTable<Game>();

  const defaultParams = ref<GameSearchParams>({
    createFrom: 2,
    approveStates: [0],
  });
  const searchParams = ref<GameSearchParams>({});

  const getData = async () => {
    loading.value = true;
    try {
      const res = await getGameList({
        ...pager.value,
        ...searchParams.value,
        ...defaultParams.value,
      });
      total.value = res?.data?.data?.total || 0;
      list.value = res?.data?.data?.list || [];
    } finally {
      loading.value = false;
    }
  };

  const handleSearch = (params: GameSearchParams) => {
    pager.value.pageIndex = 1;
    searchParams.value = params;
    getData();
  };

  const handlePageIndexChanged = (pageIndex: number) => {
    pager.value.pageIndex = pageIndex;
    getData();
  };

  onMounted(() => {
    getData();
  });

  const handleMenuClicked = async (game: Game, action: string) => {
    switch (action) {
      case 'DETAIL': {
        const routeInfo = router.resolve({
          name: 'GameDetailApp',
          query: {
            id: game.id,
          },
        });
        window.open(routeInfo.href);
        break;
      }
      case 'EDIT': {
        const routeInfo = router.resolve({
          name: 'GameEditorApp',
          query: {
            id: game.id,
          },
        });
        window.open(routeInfo.href);
        break;
      }
      case 'ARRAIGN': {
        await publishGame(game.id);
        getData();
        Message.success('已提交审核');
        break;
      }
      case 'DELETE': {
        Modal.confirm({
          title: '确定删除该赛事？',
          content: '删除后无法恢复',
          onOk: async () => {
            await deleteGame(game.id);
            Message.success('已删除');
            getData();
          },
        });
        break;
      }
      default: {
        break;
      }
    }
  };
</script>

<template>
  <div style="padding: 20px">
    <a-row :gutter="[20, 20]">
      <a-col>
        <a-card title="待审核赛事" :bordered="false">
          <SearchForm @submit="handleSearch" />
        </a-card>
      </a-col>

      <a-col>
        <a-card :bordered="false">
          <a-table
            :bordered="{ cell: true }"
            :data="list"
            :loading="loading"
            :pagination="{
              total,
              current: pager.pageIndex,
              pageSize: pager.pageSize,
              showTotal: true,
              showJumper: true,
            }"
            @page-change="handlePageIndexChanged"
          >
            <template #columns>
              <a-table-column
                title="赛事"
                data-index="name"
                fixed="left"
                :width="300"
              >
                <template #cell="{ record }">
                  <GameCard :game-info="record" />
                </template>
              </a-table-column>
              <a-table-column title="级别" data-index="phone" :width="100">
                <template #cell="{ record }">
                  {{
                    GameRegionLevels.find((i) => i.value === record.regionLevel)
                      ?.label
                  }}
                </template>
              </a-table-column>
              <a-table-column title="类型" data-index="phone" :width="100">
                <template #cell="{ record }">
                  {{ GameTypes.find((i) => i.value === record.type)?.label }}
                </template>
              </a-table-column>
              <a-table-column title="方式" data-index="phone" :width="100">
                <template #cell="{ record }">
                  {{
                    GameGroupTypes.filter(
                      (i) => (i.value & record.groupType) === i.value
                    )
                      .map((i) => i.label)
                      .join('，')
                  }}
                </template>
              </a-table-column>
              <a-table-column title="地区" data-index="phone" :width="200">
                <template #cell="{ record }">
                  {{
                    ProvinceJSON.find((i) => i.id === record.province)?.name
                  }}/{{
                    CityJSON[record.province as keyof typeof CityJSON].find(
                      (i) => i.id === record.city
                    )?.name
                  }}
                </template>
              </a-table-column>
              <a-table-column
                title="创建人"
                data-index="creator.nickname"
                :width="150"
              >
              </a-table-column>
              <a-table-column
                title="创建时间"
                data-index="gmtCreate"
                :width="200"
              >
                <template #cell="{ record }">
                  {{ dayjs(record.gmtCreate).format('YYYY/MM/DD HH:mm:ss') }}
                </template>
              </a-table-column>
              <!-- <a-table-column
                title="状态"
                align="center"
                data-index="approveState"
                :width="120"
              >
                <template #cell="{ record }">
                  <a-tag
                    :color="
                      ['gray', 'blue', 'green', 'red'][record.approveState + 1]
                    "
                  >
                    {{
                      GameApproveState.find(
                        (i) => i.value === record.approveState
                      )?.label
                    }}
                  </a-tag>
                </template>
              </a-table-column> -->
              <!-- <a-table-column
                title="进程"
                align="center"
                data-index="state"
                :width="120"
              >
                <template #cell="{ record }">
                  <a-tag
                    :color="
                      ['gray', 'blue', 'blue', 'green', 'orange'][record.state]
                    "
                  >
                    {{
                      GameStates.find((i) => i.value === record.state)?.label
                    }}
                  </a-tag>
                </template>
              </a-table-column> -->
              <a-table-column
                title="操作"
                align="center"
                :width="120"
                fixed="right"
              >
                <template #cell="{ record }">
                  <a-dropdown
                    @select="handleMenuClicked(record, $event as string)"
                  >
                    <a-link> 操作 </a-link>
                    <template #content>
                      <a-doption value="DETAIL">查看详情</a-doption>
                      <a-doption
                        value="EDIT"
                        :disabled="record.approveState !== -1"
                      >
                        编辑
                      </a-doption>
                      <a-doption disabled value="DELETE"> 删除 </a-doption>
                    </template>
                  </a-dropdown>
                </template>
              </a-table-column>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>
